package com.ntv.presentation.spring.web.wishes;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.ntv.domain.IWishes;
import com.ntv.domain.Wishes;
import com.ntv.service.DomainException;
import com.ntv.service.wishes.IWishesAppService;

@Controller
@RequestMapping("/wishesentry.html")
public class WishesEntryFormController {
	private static final Logger logger = Logger
			.getLogger(WishesEntryFormController.class);
	
	@Autowired
	private IWishesAppService wishesAppService;

	/**
	 * @param wishesAppService
	 *            the wishesAppService to set
	 */
	public void setWishesAppService(IWishesAppService wishesAppService) {
		this.wishesAppService = wishesAppService;
	}

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		logger.info(" initBinder of wishes entry controller ");
		binder.setAllowedFields(new String[] { "fullnameWhoIs", "nativePlace", "fullnameWhomTo", "subject", "message", "publishDateString"});
	}

	private static final String MA_WISHES = "wishes";

	@RequestMapping(method = RequestMethod.POST)
	public String form(@ModelAttribute(MA_WISHES) Wishes wishes, @RequestParam("multipartFile") MultipartFile multipartFile, ModelMap model) {
		try
		{
			wishes.setImage(multipartFile.getInputStream());
			this.wishesAppService.saveWish(wishes);
			logger.info("wish is inserted successfully...");
			return "redirect:/wishesentry.html";
		}
		catch (DomainException e)
		{
			logger.error(e);
			e.printStackTrace();
			return "redirect:/wishesentry.html";
		} catch (IOException e) {
			logger.error(e);
			e.printStackTrace();
			return "redirect:/wishesentry.html";
		}
	}
	
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView form(Model modelll) throws Exception {
		// ModelAndView mav = new ModelAndView();
		modelll.addAttribute(MA_WISHES, new Wishes());
		List<IWishes> wishesList = wishesAppService.getCurrentDayWishes();
		logger.debug(" List Size " + wishesList.size());
		Map model = new HashMap();
		model.put("wishesList", wishesList);
		ModelAndView mav = new ModelAndView("home.wishes.entry", model);
		return mav;
	}

}
